package ewgenius.xube.engine.graphics.gui;

import java.util.ArrayList;

import org.lwjgl.util.Rectangle;
import org.lwjgl.util.vector.Vector2f;
import org.newdawn.slick.TrueTypeFont;

import ewgenius.xube.XubeEngine;
import ewgenius.xube.engine.IUpdateable;
import ewgenius.xube.engine.graphics.IDrawable;
import ewgenius.xube.engine.graphics.Render;

public class Gui implements IDrawable, IUpdateable, Comparable<Gui> {
	protected Vector2f location = new Vector2f();
	protected Vector2f position = new Vector2f();
	protected int width;
	protected int height;
	protected Gui parent;
	protected GuiCollection container;
	protected ArrayList<Gui> children = new ArrayList<Gui>();
	protected boolean dragging = false;
	protected int zindex = 0;
	protected Rectangle activeArea = new Rectangle();

	public void setLocation(Vector2f location) {
		this.location = location;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public Vector2f getPosition() {
		if (parent != null) {
			Vector2f parent_position = parent.getPosition();
			position = new Vector2f(location.x + parent_position.x, location.y
					+ parent_position.y);
		} else
			position = location;

		return position;
	}

	@Override
	public void render(Render render) {
	}

	@Override
	public void update(int time, XubeEngine engine) {
	}
	
	public void click() {};
	
	public void drag(XubeEngine engine) {
		int x1 = activeArea.getX() + (int)position.x;
		int x2 = x1 + activeArea.getWidth();
		int y1 = activeArea.getY() + (int)position.y;
		int y2 = y1 + activeArea.getHeight();
		
		if (!engine.getInputState().mouseIsDragging && !dragging
				&& engine.getInputState().checkMouseInArea(x1, y2 - height, x1+width, y2)
				&& engine.getInputState().mouseButton[0]) {
			zindex = -1;
			container.push();
		}
		if (!engine.getInputState().mouseIsDragging && !dragging
				&& engine.getInputState().checkMouseInArea(x1, y1, x2, y2)
				&& engine.getInputState().mouseButton[0]) {
			dragging = true;
			engine.getInputState().mouseIsDragging = true;
			zindex = -1;
			container.organize();
		}
		if (!engine.getInputState().mouseButton[0]) {
			dragging = false;
			click();
			engine.getInputState().mouseIsDragging = false;
		}
		if (dragging) {
			location.setX(location.x + engine.getInputState().mouseDX);
			location.setY(location.y + engine.getInputState().mouseDY);
		}
	}
	
	public void close() {
		container.remove(this);
	}

	@Override
	public int compareTo(Gui o) {
		if (o.zindex < zindex)
			return -1;
		if (o.zindex > zindex)
			return 1;
		return 0;
	}
}
